package org.andao.core.support.document;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.List;

import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.rtf.RTFEditorKit;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.rtf.RtfWriter2;

/**
 * RTF文档编辑器.提供RTF文件的读写转换功能.
 *
 * @author Seewo Software - Marco.hu(huzhiguo@cvte.cn)
 *
 */
public class RtfDocumentEditor {

	/**
	 * html文档转为RTF.
	 * @param storePath
	 * @param htmlContent
	 * @param rectangle
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static void htmlToRtfBuilder(String storePath,String htmlContent,Rectangle rectangle)
						throws IOException, DocumentException{
		Paragraph context = new Paragraph();  		
		Document document = getDocument(rectangle, storePath);
		StyleSheet ss = new StyleSheet();  //默认样式
		List<?> htmlList = HTMLWorker.parseToList(new StringReader(htmlContent), ss);  
	    for(int i=0;i<htmlList.size();i++){  //解析HTML	     
	         context.add((Element)htmlList.get(i));  
	     }  
	    document.add(context);  //创建
	    closeDocument(document);//关闭		
	}
	
	/**
	 * 读取RTF文件.<p>
	 * NOTICE: 提取文本，读取中文需要使用ISO8859_1编码，否则会出现乱码.
	 * @param filePath
	 * @return
	 * @throws BadLocationException 
	 * @throws IOException 
	 */
	public static String getTextFromRtf(String filePath) throws BadLocationException, IOException {
		String result = null;
		File file = new File(filePath);
		RTFEditorKit rtf = new RTFEditorKit();		
		DefaultStyledDocument styledDoc = new DefaultStyledDocument();
		InputStream is = new FileInputStream(file);
		rtf.read(is, styledDoc, 0);		
		String encode = getEncoding(styledDoc.getText(0, styledDoc.getLength()));
		if(encode.equals("UTF-8") || encode.equals("ISO-8859-1")){
			result = new String(styledDoc.getText(0, styledDoc.getLength()).getBytes("ISO-8859-1"),"GBK");
		}else{
			result = new String(styledDoc.getText(0, styledDoc.getLength()).getBytes(encode),"GBK");
		}					
		return result;
	}
	
	private static String getEncoding(String str) { 
		String encode = "ISO-8859-1";   
	    try {   
	           if (str.equals(new String(str.getBytes(encode), encode))) {  	                
	               return encode;   
	            }   
	        } catch (Exception exception1) {   
	      }   
       encode = "GB2312";   
       try {   
           if (str.equals(new String(str.getBytes(encode), encode))) {               
               return encode;   
            }   
        } catch (Exception exception) {   
        }   
       
       encode = "UTF-8";   
       try {   
           if (str.equals(new String(str.getBytes(encode), encode))) {                    
               return encode;   
            }   
        } catch (Exception exception2) {   
        }   
        encode = "GBK";   
       try {   
           if (str.equals(new String(str.getBytes(encode), encode))) {                
               return encode;   
            }   
        } catch (Exception exception3) {   
        }   
       return encode;   
    }   
	
	private static Document getDocument(Rectangle rectangle,String storePath) throws FileNotFoundException{
		Rectangle defaultRectangel = PageSize.A4;
		if(null != rectangle){
			defaultRectangel = rectangle;
		}
		Document document = new Document(defaultRectangel);
		RtfWriter2.getInstance(document, new FileOutputStream(storePath));
		document.open();		
		return document;
	}

	private static void closeDocument(Document document){
		if (null != document) {
			document.close();
		}
	}
}
